﻿using Furion.DependencyInjection;
using IndoorPosition.Server.Core.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IndoorPosition.Server.Application
{   
    /// <summary>
    /// 地理数据相关逻辑代码
    /// </summary>
    public class GeoDataService : IGeoDataService, ITransient
    {
        IConfigurationService _configurationService;

        public GeoDataService(IConfigurationService configurationService)
        { 
            _configurationService = configurationService;
        }

        /// <summary>
        /// 保存地理数据（GeoJson）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<FeatureClassMeta> StoreAsync(GeoDataInputDto input)
        {
            var host = (await _configurationService.GetAsync("postgis_host")).Value;
            var port = (await _configurationService.GetAsync("postgis_port")).Value;
            var db = (await _configurationService.GetAsync("postgis_db")).Value;
            var user = (await _configurationService.GetAsync("postgis_user")).Value;
            var password = (await _configurationService.GetAsync("postgis_password")).Value;
            var postgisUtil = new PostGISUtil(host,Convert.ToInt32(port),db,user,password);

            return postgisUtil.Save(input.Name, input.GeoJson);
        }

        /// <summary>
        /// 数据是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<bool> DataExistAsync(string name)
        {
            var host = (await _configurationService.GetAsync("postgis_host")).Value;
            var port = (await _configurationService.GetAsync("postgis_port")).Value;
            var db = (await _configurationService.GetAsync("postgis_db")).Value;
            var user = (await _configurationService.GetAsync("postgis_user")).Value;
            var password = (await _configurationService.GetAsync("postgis_password")).Value;
            var postgisUtil = new PostGISUtil(host, Convert.ToInt32(port), db, user, password);

            return postgisUtil.TableExist(name);
        }

        /// <summary>
        /// 删除表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task DeleteDataAsync(string name)
        {
            var host = (await _configurationService.GetAsync("postgis_host")).Value;
            var port = (await _configurationService.GetAsync("postgis_port")).Value;
            var db = (await _configurationService.GetAsync("postgis_db")).Value;
            var user = (await _configurationService.GetAsync("postgis_user")).Value;
            var password = (await _configurationService.GetAsync("postgis_password")).Value;
            var postgisUtil = new PostGISUtil(host, Convert.ToInt32(port), db, user, password);

            postgisUtil.DeleteTable(name);
        }
    }
}
